package edu.ustb.services.weatherforecast.service;

import edu.ustb.services.weatherforecast.entity.CityWeather;
import edu.ustb.services.weatherforecast.entity.SampleWeather;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

@Service
public class WeatherForecastService {

    private static Map<Integer,SampleWeather> sampleWeatherMap = new HashMap<>();
    private static String[] weather = {"晴", "多云", "雨"};
    private static String[] windPower = {"1级", "2级", "3级", "4级", "5级"};
    private static String[] windDirect = {"东风", "东南风", "南风", "西南风", "西风", "西北风", "北风", "东北风"};
    private static DecimalFormat df = new DecimalFormat("######0.0");

    @Autowired
    public WeatherForecastService() {
        initSampleWeatherMap();
    }

    public static void initSampleWeatherMap() {
        Random r = new Random();
        SampleWeather sampleWeather = null;
        for (int i=0; i < 7; i++) {
            sampleWeather = new SampleWeather(weather[r.nextInt(3)], 10+(20*r.nextDouble()), 10-(20*r.nextDouble()), 600+r.nextInt(500), windPower[r.nextInt(5)], windDirect[r.nextInt(8)]);
            sampleWeatherMap.put(i+1, sampleWeather);
        }

    }

    public Map<String,Object> getCityWeather( String cityName, String date) {
        LinkedHashMap<String,Object> queryResult = new LinkedHashMap<>();
        queryResult.put("城市名", cityName);
        // queryResult.put("城市ID", cityId);
        queryResult.put("日期", date);
        queryResult.put("今日天气", sampleWeatherMap.get(1));

        return queryResult;
    }

    public Map getCityWeatherBack( String cityName, String cityId, int date) {
        LinkedHashMap<String,Object> queryResult = new LinkedHashMap<>();
        queryResult.put("城市名", cityName);
        queryResult.put("城市ID",cityId);
        for (int i=1; i <= date; i++) {
            queryResult.put("第"+i+"天", sampleWeatherMap.get(i));
        }

        return queryResult;
    }

    /**
     * use weather template to set CityWeather
     * @param cityName
     * @param cityId
     * @param date
     * @param sampleWeather
     * @return
     */
    public CityWeather setCityWeather(String cityName, Integer cityId, String date, SampleWeather sampleWeather) {
        CityWeather cityWeather = new CityWeather(
                cityId,
                cityName,
                date,
                sampleWeather.getWeather(),
                sampleWeather.getTempHigh(),
                sampleWeather.getTempLow(),
                sampleWeather.getPressure(),
                sampleWeather.getWindDirect(),
                sampleWeather.getWindPower()
        );
        return cityWeather;
    }
}
